package cn.itcast.tools.java发送文件.模拟表单;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//https://www.icode9.com/content-1-1103717.html
public class FileUpload {
    //boundary 的值随机即可
    static String boundary = "----WebKitFormBoundaryeIAzkhBx5AozTHAY";
    static String prefix = "--";
    static String newLine = "\r\n";


    public static void main(String[] args) {
        test();
    }

    private static void test() {
        try {
            URL url = new URL("http://30.210.208.127:5005/sss");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + boundary);
            connection.connect();
            ConfigHttpMultipart(connection.getOutputStream());
            InputStream ins = connection.getInputStream();
            byte[] b = readBuffer(ins);
            System.out.println(new String(b,"UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void ConfigHttpMultipart(final OutputStream out) throws Exception{
        StringBuffer params = new StringBuffer();
        Map<String, String> textMap = initTextMap();
        for (Map.Entry<String, String> map : textMap.entrySet()) {
            // 注意换行符或--不要太多，太多导致数据无法传输
            params.append(newLine + prefix + boundary + newLine);
            params.append("Content-Disposition: form-data; name=\"" + map.getKey() + "\"");
            params.append(newLine + newLine);
            params.append(map.getValue());
        }
        // 隔开文本与文件
        params.append(newLine);
        out.write(params.toString().getBytes("UTF-8"));

        List<String> fileList = initFileList();
        for(int i = 0; i < fileList.size(); i++){
            //添加参数file
            File file = new File(fileList.get(i));
            StringBuffer sb = new StringBuffer();
            sb.append(newLine + prefix + boundary + newLine);
            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"");
            sb.append(newLine);
            sb.append("Content-Type: multipart/form-data; boundary=" + boundary);
            sb.append(newLine + newLine);
            out.write(sb.toString().getBytes("utf-8"));

            InputStream in = new FileInputStream(file);
            byte b[] = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.write(prefix.getBytes());
            in.close();
        }
        byte[] end_data = (newLine + prefix + boundary + prefix + newLine).getBytes();
        out.write(end_data);

        out.flush();
        out.close();
    }

    private static List<String> initFileList() {
        List<String> list = new ArrayList<String>();
        list.add("/Users/feiyi-lgh/Documents/projectSrc/javaSrc/个人学习/java-tutorial/base/src/main/java/cn/itcast/tools/java发送文件/模拟表单/2021_9_18_17109_94377.wav");
//        list.add("F:\\工作\\2021-07\\print.xlsx");
        return list;
    }

    private static Map<String, String> initTextMap() {
        Map<String, String> param = new HashMap<String, String>();
        param.put("userAccount", "ceshi");
        return param;
    }

    public static byte[] readBuffer(final InputStream ins) throws IOException {
        byte b[] = new byte[1024];
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        int len = 0;
        while ((len = ins.read(b)) != -1) {
            stream.write(b, 0, len);
        }
        return stream.toByteArray();
    }

}


//        System.out.println(up.send("http://30.210.208.127:5004/upload","/Users/feiyi-lgh/Documents/projectSrc/javaSrc/个人学习/java-tutorial/base/src/main/java/cn/itcast/tools/java发送文件/模拟表单/io2.txt"));